using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using Random = Unity.Mathematics.Random;


[CreateAssetMenu(menuName="Data/ProcedureTextureGenerater")]
    public class ProcedureTextureGenerater : ScriptableObject
    {
        [SerializeField]
        public int width;
        
        [SerializeField]
        public int height;

        [SerializeField] public int cell;
        
        [SerializeField]
        public ComputeShader cs = null;

        [SerializeField] public string texName = "";
        
        public void DoGen()
        {
            Debug.LogFormat("ProcedureTextureGenerate DoGen");

            RenderTexture rt = new RenderTexture(width, height, 0);
            rt.enableRandomWrite = true;
            rt.Create();

            int widthCount = width / cell + 1;
            int heightCount = height / cell + 1;
            
            float[] gradbuffer = new float[2 * (widthCount + 1) * (heightCount + 1)];

            for (int i = 0; i <= widthCount; i++)
            {
                for (int j = 0; j <= heightCount; j++)
                {
                    int index = i * heightCount + j;
                    Debug.LogFormat("aaaa {0}", index);
                    float theta = UnityEngine.Random.Range(0, UnityEngine.Mathf.PI);
                    
                    gradbuffer[2 * index] = UnityEngine.Mathf.Sin(theta);
                    gradbuffer[2 * index + 1] = UnityEngine.Mathf.Cos(theta);
                }
            }

            ComputeBuffer computeBuffer = new ComputeBuffer((widthCount + 1) * (heightCount + 1), 2 * 4, ComputeBufferType.Default);
            computeBuffer.SetData(gradbuffer);
            
            int kernel = cs.FindKernel("CSMain");
            cs.SetTexture(kernel, "Result", rt);
            cs.SetBuffer(kernel, "GradBuffer", computeBuffer);
            cs.SetInt("wCount", widthCount);
            cs.SetInt("hCount", heightCount);
            cs.SetInt("cell", cell);
            cs.Dispatch(kernel, width / 8, height / 8 , 1);
            Texture2D tex = toTexture2D(rt);
            
            byte[] bytes;
            bytes = tex.EncodeToPNG();

            string absPath = Path.Combine(Application.streamingAssetsPath, "../Textures/", texName);
            string relativePath = Path.Combine("Assets", "Textures", texName);
            File.WriteAllBytes(absPath, bytes);
            AssetDatabase.ImportAsset(relativePath);
            
            computeBuffer.Dispose();
        }
        
        private Texture2D toTexture2D(RenderTexture rTex)
        {
            Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
            // ReadPixels looks at the active RenderTexture.
            RenderTexture.active = rTex;
            tex.ReadPixels(new Rect(0, 0, rTex.width, rTex.height), 0, 0);
            tex.Apply();
            return tex;
        }
        
    }
